<template>
  <div class="lb-account">
    <lb-title></lb-title>
    <div class="page-main">
      <el-row class="page-top-operate">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addOrAddAccountInfo('add')"
          >新增账户</el-button
        >
      </el-row>

      <div class="page-top-operate form-search">
        <el-form @submit.native.prevent :inline="true" :model="pageForm">
          <el-form-item label="账户名/小程序名称">
            <el-input
              v-model="pageForm.name"
              placeholder="请输入账户名/小程序名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <lb-button type="primary" @click="getTableDataList(1)">{{
            $t('action.search')
          }}</lb-button>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="account" label="账户名"> </el-table-column>
        <el-table-column prop="description" label="角色"> </el-table-column>
        <el-table-column prop="mini_name" label="小程序名称"> </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <el-button
                type="primary"
                size="mini"
                plain
                @click="addOrAddAccountInfo('edit', scope.row)"
                >{{ $t('action.edit') }}</el-button
              >
              <el-button
                type="danger"
                size="mini"
                plain
                @click="delUserInfo(scope.row.admin_id)"
                v-if="scope.row.account !== 'admin'"
                >{{ $t('action.delete') }}</el-button
              >
              <el-button
                type="primary"
                size="mini"
                plain
                @click="openMiniApp(scope.row.admin_id)"
                v-if="scope.row.account !== 'admin' && !scope.row.is_bind"
                >绑定小程序</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :page="pageForm.page"
        :pageSize="pageForm.page_count"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
      <el-dialog
        :title="dialogTitle"
        :visible.sync="centerDialogVisible"
        width="400px"
        center
      >
        <el-form
          @submit.native.prevent
          :model="accountForm"
          :rules="accountFormRules"
          ref="accountForm"
          label-width="80px"
        >
          <el-form-item label="账户身份" prop="level">
            <el-radio-group v-model="accountForm.level">
              <el-radio :label="0">{{
                isSuperAdmin ? '超级管理员' : '管理员'
              }}</el-radio>
              <el-radio :label="1" v-if="isSaasAuth && !isSuperAdmin"
                >员工</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="账户名" prop="account">
            <el-input
              :disabled="oType === 'add' ? false : true"
              v-model="accountForm.account"
              placeholder="请输入账户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="passwd">
            <el-input
              v-model="accountForm.passwd"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('accountForm')">{{
            $t('action.comfirm')
          }}</el-button>
          <el-button @click="centerDialogVisible = false">{{
            $t('action.cancel')
          }}</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="绑定小程序"
        :visible.sync="miniAppDialog"
        width="400px"
        center
      >
        <div class="dialog-inner">
          <el-select
            v-model="appForm.modular_id"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in miappOptions"
              :key="item.modular_id"
              :label="item.mini_name"
              :value="item.modular_id"
            >
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="bindMiniApp">{{
            $t('action.comfirm')
          }}</el-button>
          <el-button @click="miniAppDialog = false">{{
            $t('action.cancel')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data () {
    let validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if (!/^(\S){6,20}$/.test(value)) {
        callback(new Error('请输入6-20位非空白符的字符!'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      centerDialogVisible: false,
      dialogTitle: '',
      miniAppDialog: false,
      pageForm: {
        page: 1,
        page_count: 10,
        name: ''
      },
      accountForm: {
        level: 0,
        account: '',
        passwd: ''
      },
      accountFormRules: {
        level: { required: true, type: 'number', message: '请选择账户身份', trigger: 'blur' },
        account: {
          required: true,
          type: 'string',
          message: '请输入账户名',
          trigger: 'blur'
        },
        passwd: {
          required: true,
          type: 'string',
          validator: validatePassword,
          trigger: 'blur'
        }
      },
      tableData: [],
      total: 0,
      oType: '',
      miappOptions: [],
      appForm: {
        admin_id: '',
        modular_id: ''
      },
      version: false,
      isSaasAuth: false,
      isSuperAdmin: false
    }
  },
  created () {
    this.getminiAppList()
    this.version = JSON.parse(localStorage.getItem('vs'))
    console.log(typeof this.version)
  },
  activated () {
    this.getTableDataList()
  },
  methods: {
    getTableDataList (flag) {
      this.loading = true
      if (flag) this.pageForm.page = 1
      let {
        pageForm
      } = this
      this.$api.getUserList(pageForm).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
          this.isSaasAuth = res.data.zhihuituike
        }
      })
    },
    addOrAddAccountInfo (type, info) {
      this.accountForm = type === 'add' ? {
        level: 0,
        account: '',
        passwd: ''
      } : {
        level: info.level,
        account: info.account,
        passwd: info.passwd,
        admin_id: info.admin_id
      }
      this.dialogTitle = type === 'add' ? '添加账户' : '编辑账户'
      this.centerDialogVisible = true
      this.oType = type
      this.isSuperAdmin = !!(type === 'edit' && info.account === 'admin')
    },
    openMiniApp (id) {
      this.miniAppDialog = true
      this.appForm.admin_id = id
    },
    bindMiniApp (id) {
      let {
        appForm
      } = this
      if (!appForm.modular_id) {
        this.$message.error('请先选择小程序')
      } else {
        this.$api.bindAccountMiniApp(appForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successSub'))
            this.miniAppDialog = false
            this.getTableDataList()
          }
        })
      }
    },
    getminiAppList () {
      this.$api.getAllMiniApp().then(res => {
        if (res.code === 200) {
          this.miappOptions = res.data
        }
      })
    },
    submitForm (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          let methodModel = this.oType === 'add' ? 'createAccountInfo' : 'editAccountInfo'
          this.$api[methodModel](this.accountForm).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.getTableDataList()
              this.centerDialogVisible = false
            }
          })
        }
      })
    },
    delUserInfo (id) {
      this.$confirm(this.$t('tips.confirmDelete') + '删除后将无法恢复！', this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.$api.delAccountInfo({
          admin_id: id
        }).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successDel'))
            this.getTableDataList()
          }
        })
      })
    },
    handleSizeChange (val) {
      this.pageForm.page_count = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.pageForm.page = val
      this.getTableDataList()
    }
  },
  watch: {
    miniAppDialog (newValue) {
      this.appForm.modular_id = !newValue ? '' : this.appForm.modular_id
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog {
  .el-form {
    .el-input {
      width: 260px;
    }
  }
}
.lb-account {
  width: 100%;
}

.dialog-inner {
  display: flex;
  min-height: 100px;
  justify-content: center;
  .el-select {
    width: 260px;
  }
}
</style>
